<?php
	require_once 'include/lsamp_curl.php';
	require_once 'config.php';
	error_log(date("d/m/y H:i:s") . " | ------- \n",3,$log_file);
	error_log(date("d/m/y H:i:s") . " | " . "Start cron job \n",3,$log_file);
	$hmg_client = new lsamp_cURL(TRUE, 'hmg_cookies.txt', 'gzip', '', 'https://www.hmgcommerce.com');
	$hmg_login_url = 'https://www.hmgcommerce.com/login.asp';
	$hmg_login_data = 'username=' . $hmg_username
					. '&password=' . $hmg_password
					. '&remember_me=on'
					. '&div=HHI'
					. '&login=Log+In';
	$result = $hmg_client->post($hmg_login_url, $hmg_login_data, $errno, $error);
	if($errno != 0){
		error_log(date("d/m/y H:i:s") . " | " . "Error: " . $error . "\n",3,$log_file);
		exit;
	}else{
		error_log(date("d/m/y H:i:s") .  " | " ."Login information posted \n" , 3, $log_file);
	}
	// load xml file to dom
	$dom = new DOMDocument();
	$dom->load($xml_filename);
	
	foreach($products as $product){
		//parse query variables from the product link
		list($product["ref"], $tmp) = split("\&", $product['link'], 2);
		$stocklevel = fetch_product_stocklevel($hmg_client, $product, $log_file);
		echo $product["sku"] . " - " . $stocklevel . "\n";
		if($stocklevel >= 0)
		update_stocklevel_inxml($dom, $product, $stocklevel);
		sleep(5);
	}
	//
	error_log(date("d/m/y H:i:s") . " | " .  "Update the $xml_filename file \n",3,$log_file);
	$dom->save($xml_filename);
	
	error_log(date("d/m/y H:i:s") . " | " . "End cron job \n",3,$log_file);

	/**
	 * Fetch the stock level from the hmg site of a product
	 *
	 * @param cURL_client $hmg_client
	 * @param array $product_cfg
	 * @param string $hmg_catalog_url
	 */
	function fetch_product_stocklevel($hmg_client, $product_cfg, $log_file){
		$stock_level = 0;
		
		$product_page = $hmg_client->get($product_cfg["link"], $errno, $error, $product_cfg["ref"]);
		if($errno != 0){
			error_log(date("d/m/y H:i:s") . " | " . "Error when fetching " . $product_cfg['sku'] . ": " . $error . "\n",3,$log_file);
			return -1;
		}else{
			error_log(date("d/m/y H:i:s") .  " | " ."Fetched product information of the" . $product_cfg['sku'] . " \n" , 3, $log_file);
		}

		$ret = preg_match_all('#<tr class="OFLocationRow">((?:.(?!/tr>))+)#', $product_page, $matches);
		if($ret > 0){
			foreach($matches[1] as $stock_by_location){
				$ret = preg_match('#<strong>((?:.(?!/strong>))+)#', $stock_by_location, $stock_matches);
				if($ret > 0){
					$stock_level += $stock_matches[1];
				}else{
					error_log(date("d/m/y H:i:s") . " | " . "Error when fetching " . $product_cfg['sku'] . ": format changed \n",3,$log_file);
					return -1;
				}
			}
		}else{
			error_log(date("d/m/y H:i:s") . " | " . "Error when fetching " . $product_cfg['sku'] . ": format changed \n",3,$log_file);
			return -1;
		}
		return $stock_level;
	}

	/**
	 * Update the stock level to the xml file
	 * 
	 * @param DOMDocument $xml_dom
	 * @param array $product_cfg
	 * @param int $stocklevel
	 * @return 
	 */
	function update_stocklevel_inxml(&$xml_dom, $product_cfg, $stocklevel){
		// find the element with the sku
		$xpath = new DOMXPath($xml_dom);
		$skus = $xpath->query("//Products/Product/ProductSKU");
		$match = false;
		foreach($skus as $sku){
			if($sku->nodeValue == $product_cfg["sku"]){
				$match = true;
				$stocklevel_elements = $sku->parentNode->getElementsByTagName("StockLevel"); // find the StockLevel element to update
				if($stocklevel_elements->length == 0){ 										// not found, create one
					$stocklevel_element = $xml_dom->createElement("StockLevel", $stocklevel);		
					$sku->parentNode->appendChild($stocklevel_element);
				}else{																		// found, update
					$stocklevel_elements->item(0)->nodeValue = $stocklevel;					
				}								
			}
		}
		
		if($match == false){	// the product with the specified sku does not exist, create one
			$product = $xml_dom->createElement("Product");
			$sku_element = $xml_dom->createElement("ProductSKU", $product_cfg['sku']);
			$product->appendChild($sku_element);
			$stocklevel_element = $xml_dom->createElement("StockLevel", $stocklevel);
			$product->appendChild($stocklevel_element);	
			$xml_dom->getElementsByTagName("Products")->item(0)->appendChild($product);		
		}
	}
?>
